package com.example.kotlinlearn.premission

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.Adapter
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.kotlinlearn.BaseActivity
import com.example.kotlinlearn.R
import com.example.kotlinlearn.databinding.ActivityPremissionBinding
import java.io.IOException
import java.util.jar.Manifest

class PremissionActivity : BaseActivity() {

    private lateinit var binding:ActivityPremissionBinding

    private val contactList = ArrayList<String>()
    private lateinit var adapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_premission)
        binding = ActivityPremissionBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.call.setOnClickListener {
            //判断用户是否给予我们打电话的权限
            if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.CALL_PHONE)!=
                    PackageManager.PERMISSION_GRANTED){
                        //没有权限就好调用onRequestPermissionsResult的方法来让用户给予我们权限或者不
                ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CALL_PHONE),1)
            }else{
                call()
            }
        }
        //获取联系人操作
        adapter = ArrayAdapter(this,android.R.layout.simple_list_item_activated_1,contactList)
        binding.listView.adapter =adapter
        if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.READ_CONTACTS)
        !=PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_CONTACTS),2)
        }else{
            readContacts()
        }
    }

    /**
     * 执行危险权限时必须重写这个方法
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if (grantResults.isNotEmpty()
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    call()
                }else{
                    Toast.makeText(this,"没有权限，无法执行操作",Toast.LENGTH_SHORT).show()
                }
            }
            2->{
                if (grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    readContacts()
                }else{
                    Toast.makeText(this,"你拒绝了获取联系人的权限请求",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    //获取联系人电话
    private fun readContacts(){
        contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,null,null,null)?.apply {
                while (moveToNext()){
                    //获取姓名
                    val name = getString(getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                    ))
                    //获取联系人手机号
                    val num = getString(getColumnIndex(
                        ContactsContract.CommonDataKinds.Phone.NUMBER
                    ))
                    contactList.add("$name\n$num")
                }
            //更新视图
            adapter.notifyDataSetChanged()
            //关闭查询
            close()
        }
    }

    //打电话
    private fun call(){
        try {
            val intent = Intent(Intent.ACTION_CALL)
            intent.data = Uri.parse("tel:10086")
            startActivity(intent)
        }catch (e: SecurityException){
            e.printStackTrace()
        }
    }
}